package net.qiyuesuo.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import net.qiyuesuo.pojo.FileMeta;
import net.qiyuesuo.service.AbstractService;
import net.qiyuesuo.service.FileMetaService;
import net.qiyuesuo.service.FileService;
import net.qiyuesuo.service.StorageService;
import net.qiyuesuo.utils.file.FileTransformUtils;

public class FileServiceImpl extends AbstractService implements FileService {

	//文件读取服务
	private StorageService storageService = new StorageServiceImpl();
	//元数据处理服务 更新为 存储到数据库中
	private FileMetaService fileMetaService = new FileMetaServiceImpl();;
	
	@Override
	public String saveFile(byte[] bytes) {
		//调用storageService存储文件 调用fileInfoService存储元数据
		FileMeta info = storageService.storageFile(bytes);
		fileMetaService.saveInfo(info);
		return info.getUuid();
	}

	@Override
	public String saveFile(InputStream input, long size){
		FileMeta info = storageService.storageFile(input, size);
		fileMetaService.saveInfo(info);
		return info.getUuid();
	}

	@Override
	public String saveFile(File file) {
		FileMeta info = storageService.storageFile(file.toPath());
		fileMetaService.saveInfo(info);
		return info.getUuid();
	}
	
	@Override
	public byte[] getFileThrougnBytes(String fileKey) {
		//根据uuid获取 file类型文件
		File file = storageService.getFileByKey(fileKey).toFile();
		return FileTransformUtils.fileToBytes(file);
	}

	@SuppressWarnings("resource")
	@Override
	public void getFileThrouthStream(String uuid,OutputStream output) throws Exception {
		File file = storageService.getFileByKey(uuid).toFile();
		output = new FileOutputStream(file);
	}
	
	@Override
	public FileMeta getFileInfo(String fileKey) throws Exception {
		logger.info("获取uuid为："+fileKey+"的文件的元数据信息");
		return fileMetaService.getInfo(fileKey);
	}

	@Override
	public void deleteFile(String fileKey) {
		storageService.deleteFile(fileKey);
		//删除元数据
		fileMetaService.deleteInfo(fileKey);
	}

}
